package com.net
{
	import flash.events.Event;
	import flash.utils.ByteArray;
	import flash.utils.getTimer;

	import com.net.interfaces.INotify;

	/**
	 *游戏唯一的一个套接字
	 * 负责游戏所有与服务器的实时通讯
	 * @author Michael
	 *
	 */
	public class GameSocket extends TcpSocket
	{
		private static var _instance : GameSocket;

		private var notifyList : Array = [];

		public static function get instance() : GameSocket
		{
			if (_instance == null)
			{
				_instance = new GameSocket();
			}
			return _instance;
		}

		/**
		 * 注册监听事件
		 * 如果找不到注册模块
		 * 会在把这里的事件全部发送一次
		 * @param notify
		 *
		 */
		public function registerNotify(notify : INotify) : void
		{
			var index : int = notifyList.indexOf(notify);

			if (index == -1)
			{
				notifyList.push(notify);
			}
		}

		public function removeNotify(notify : INotify) : void
		{
			var index : int = notifyList.indexOf(notify);

			if (index != -1)
			{
				notifyList.splice(index, 1);
			}
		}

		public function sendData(dataBase : DataBase) : void
		{
			send(dataBase.getCmd(), dataBase.serialize());
		}

		override protected function parsePack(module : int, pack : ByteArray) : void
		{
			var dataClass : Class = AddCmd.getClassByModule(module);

			if (dataClass == null)
			{
				return;
			}

			//取对象
			var dataBase : DataBase = new DataBase();
			dataBase.deSerialize(pack);

			var notify : INotify = _handler[module];

			if (notify)
			{
				notify.handleMessage(module, dataBase);
			}
			else
			{
				for each (notify in notifyList)
				{
					notify.handleMessage(module, dataBase);
				}
			}
		}
	}
}